package com.qdu.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

@WebServlet("/getUserInfo")
public class GetUserInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String dbURL;
    private String dbUser;
    private String dbPassword;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        dbURL = config.getServletContext().getInitParameter("dbURL");
        dbUser = config.getServletContext().getInitParameter("dbUser");
        dbPassword = config.getServletContext().getInitParameter("dbPassword");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        JSONObject userInfo = new JSONObject();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(dbURL, dbUser, dbPassword);
            String sql = "SELECT username, avatar_url FROM users WHERE user_id = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, 1); // 假设user_id为1用于演示
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                String username = resultSet.getString("username");
                String avatarUrl = resultSet.getString("avatar_url");
                userInfo.put("username", username);
                userInfo.put("avatar_url", avatarUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
            if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
            if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
        }

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(userInfo.toString());
        out.flush();
    }
}
